package com.ljkj.cordial.chat.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.protobuf.ByteString;
import com.hw.videoprocessor.VideoProcessor;
import com.hw.videoprocessor.util.VideoProgressListener;
import com.lanjiu.lib.business.FileTransmissionManager;
import com.lanjiu.lib.business.OriginalPictureVideoTransmissionCreator;
import com.lanjiu.lib.business.listener.FileTransmissionListener;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.pro.file.OriginalPictureVideoFriendsTransmission;
import com.lanjiu.pro.file.OriginalPictureVideoGroupTransmission;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.dao.AlbumTableBean;
import com.ljkj.cordial.chat.dao.AlbumTableBeanDao;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.chat.widget.NetProgressBarDialog;
import com.ljkj.cordial.lengthtcpheartbeat.ByteStringUtil;
import com.nic.view.util.AndroidFileUtil;
import com.nic.view.util.FileSizeUtil;
import com.nic.view.util.JLog;
import com.nic.view.util.JToast;
import com.nic.view.util.Utility;
import com.nic.view.util.glide.GlideUtil;
import com.nic.view.widget.LookLargePhotoDialog;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.CordialFile;
import com.yanzhenjie.album.api.widget.Widget;
import com.yanzhenjie.album.app.album.data.ThumbnailBuilder;
import com.yanzhenjie.album.util.AlbumUtils;

import org.greenrobot.greendao.async.AsyncOperation;
import org.greenrobot.greendao.async.AsyncOperationListener;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

public class AlbumManageUtil {
    private static class Build {
        public static AlbumManageUtil INSTANCE = new AlbumManageUtil();
    }

    public static AlbumManageUtil getInstance() {
        return Build.INSTANCE;
    }

    private NetProgressBarDialog bar;

    /**
     * Select picture, from album.
     */
    public void selectSingleImage(Activity activity, final OnAlbumResultListener onAlbumResultListener) {
        Album.image(activity)
                .singleChoice()
                .camera(true)
                .setOutPutDir(activity.getPackageName(), ChatApp.getInstance().getUserId())
//                .checkedList(mAlbumFiles)
                .widget(
                        Widget.newDarkBuilder(activity)
                                .title("照片选取")
                                .build()
                )
                .onResult(new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(@NonNull ArrayList<AlbumFile> result) {
//                        filterFile(activity, result);
                        if (onAlbumResultListener != null) {
                            onAlbumResultListener.onResult(result);
                        }
                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        if (onAlbumResultListener != null) {
                            onAlbumResultListener.onCancel(result);
                        }
                    }
                })
                .start();
    }

    /**
     * Select picture, from album.
     */
    public void selectMultiImage(Activity activity, final OnAlbumBindResultListener onAlbumResultListener) {
        Album.image(activity)
                .multipleChoice()
                .setOutPutDir(activity.getPackageName(), ChatApp.getInstance().getUserId())
                .columnCount(2)
                .selectCount(6)
//                .camera(true)
//                .checkedList(mAlbumFiles)
                .widget(
                        Widget.newDarkBuilder(activity)
                                .title("图片和视频")
                                .build()
                )
                .onBindResult(new Action<CordialFile<ArrayList<AlbumFile>>>() {
                    @Override
                    public void onAction(@NonNull CordialFile<ArrayList<AlbumFile>> result) {
//                        if (result != null && result.getResult() != null && !result.getResult().isEmpty()) {
//                            filterFile(activity, result.getResult());
//                        }
                        if (onAlbumResultListener != null) {
                            onAlbumResultListener.onResult(result.isOrigin(), result.getResult());
                        }
                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        if (onAlbumResultListener != null) {
                            onAlbumResultListener.onCancel(result);
                        }
                    }
                })
                .start();
    }

//    private void filterFile(Activity activity, ArrayList<AlbumFile> result) {

//        ThumbnailBuilder tub = new ThumbnailBuilder(activity, activity.getPackageName(), ChatApp.getInstance().getUserId());
//        for (AlbumFile albumFile : result) {
//            double s = FileSizeUtil.getFileOrFilesSize(albumFile.getPath(), FileSizeUtil.SIZETYPE_MB);
//            if (s > 5.0) {
//                albumFile.setPath(tub.createThumbnailForLimitImage(albumFile.getPath()));
////                albumFile.setThumbPath(tub.createThumbnailForImage(albumFile.getPath()));
//            }
//
//        }
//    }

    public void previewImage(Context context, AlbumFile albumFile) {
        ArrayList<AlbumFile> albumFiles = new ArrayList<>();
        albumFiles.add(albumFile);
        previewImage(context, albumFiles, 0);
    }

    /**
     * Preview image, to album.
     */
    public void previewImage(Context context, ArrayList<AlbumFile> albumFiles, int selectedPosition) {
        if (albumFiles == null || albumFiles.size() == 0) {
            JToast.show(context, "no_selected", Toast.LENGTH_SHORT);
        } else {
            Album.galleryAlbum(context)
//                    .checkable(true)
                    .setOutPutDir(context.getPackageName(), ChatApp.getInstance().getUserId())
                    .checkedList(albumFiles)
//                    .currentPosition(selectedPosition)
                    .widget(
                            Widget.newDarkBuilder(context)
                                    .title("预览")
                                    .build()
                    )
                    .onResult(new Action<ArrayList<AlbumFile>>() {
                        @Override
                        public void onAction(@NonNull ArrayList<AlbumFile> result) {
                        }
                    })
                    .start();
        }
    }

    /**
     * Select picture, from album.
     */
    public void selectSingleVideo(Activity activity, OnAlbumResultListener onAlbumResultListener) {
        Album.video(activity)
                .singleChoice()
                .setOutPutDir(activity.getPackageName(), ChatApp.getInstance().getUserId())
                .camera(true)
//                .checkedList(mAlbumFiles)
                .widget(
                        Widget.newDarkBuilder(activity)
                                .title("视频选取")
                                .build()
                )
                .onResult(new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(@NonNull ArrayList<AlbumFile> result) {
                        if (onAlbumResultListener != null) {
                            onAlbumResultListener.onResult(result);
                        }
                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        if (onAlbumResultListener != null) {
                            onAlbumResultListener.onCancel(result);
                        }
                    }
                })
                .start();
    }

    /**
     * Select picture, from album.
     */
    public void selectMultiVideo(Activity activity, OnAlbumBindResultListener onAlbumResultListener) {
        Album.video(activity)
                .multipleChoice()
                .setOutPutDir(activity.getPackageName(), ChatApp.getInstance().getUserId())
                .columnCount(2)
                .selectCount(6)
                .camera(true)
//                .checkedList(mAlbumFiles)
                .widget(
                        Widget.newDarkBuilder(activity)
                                .title("视频选取")
                                .build()
                )
                .onBindResult(new Action<CordialFile<ArrayList<AlbumFile>>>() {
                    @Override
                    public void onAction(@NonNull CordialFile<ArrayList<AlbumFile>> result) {
                        if (onAlbumResultListener != null) {
                            onAlbumResultListener.onResult(result.isOrigin(), result.getResult());
                        }
                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        if (onAlbumResultListener != null) {
                            onAlbumResultListener.onCancel(result);
                        }
                    }
                })
                .start();
    }

    /**
     * 视频压缩
     *
     * @param activity
     * @param result
     * @param outputPath
     * @param videoProgressListener
     */
    public void setVideoProcessor(Activity activity, @NonNull String result, String outputPath, final VideoProgressListener videoProgressListener) {
        try {
            VideoProcessor.Processor p = VideoProcessor.processor(activity)
                    .input(result)
                    .output(outputPath)
                    //以下参数全部为可选
//                    .outWidth(1280)
//                    .outHeight(720)
//                    .startTimeMs(0)//用于剪辑视频
//                    .endTimeMs(15 * 1000)    //用于剪辑视频
                    //                                                    .speed(speed)            //改变视频速率，用于快慢放
                    //                                .changeAudioSpeed(changeAudioSpeed) //改变视频速率时，音频是否同步变化
                    .bitrate(1030 * 1024)       //输出视频比特率
                    .frameRate(30)   //帧率
                    //                    .iFrameInterval(0)  //关键帧距，为0时可输出全关键帧视频（部分机器上需为-1）
                    .progressListener(new VideoProgressListener() {
                        @Override
                        public void onProgress(float progress) {
                            if (progress == 1.0f) {
//                                File f = new File(outputPath);
//                                JLog.d(outputPath + "ST " + f.length());
                                scanFile(new MediaScannerConnection.OnScanCompletedListener() {
                                    @Override
                                    public void onScanCompleted(String path, Uri uri) {
//                                        File ff = new File(outputPath);
//                                        JLog.d(path + "EN " + ff.length());
                                        videoProgressListener.onProgress(progress);
                                    }
                                }, outputPath);
                            } else {
                                videoProgressListener.onProgress(progress);
                            }

                        }
                    });
            p.process();
        } catch (Exception e) {
            e.printStackTrace();
            videoProgressListener.onProgress(-1);
        }

    }

    public static void scanFile(MediaScannerConnection.OnScanCompletedListener listener, String... filePath) {
        try {
            MediaScannerConnection.scanFile(ChatApp.getInstance(), filePath, null,
                    listener);
        } catch (Exception e) {
        }

    }

    /**
     * 拍照
     *
     * @param activity
     * @param onAlbumResultListener
     */
    public void takePicture(Activity activity, final OnAlbumTakeResultListener onAlbumResultListener) {
        String id = ChatApp.getInstance().getUserId();
        String filePath = AlbumUtils.randomJPGPath(AlbumUtils.getAlbumImageFile(activity, activity.getPackageName(), id));
        Album.camera(activity)
                .image()
                .setOutPutDir(activity.getPackageName(), id)
                .filePath(filePath)
                .onResult(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        if (activity == null || activity.isFinishing()) {
                            return;
                        }
                        if (onAlbumResultListener != null) {
                            NetProgressBarDialog bar = new NetProgressBarDialog(activity).setDes("加载中...");
                            bar.show();
                            ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<AlbumFile>() {
                                @Override
                                public void onAction(AlbumFile obj) {
                                    onAlbumResultListener.onResult(obj);
                                    bar.dismiss();
                                }

                                @Override
                                public AlbumFile onThreadAction() {
                                    return getAlbumFile(activity, result);
                                }
                            });
                        }
                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        if (onAlbumResultListener != null) {
                            onAlbumResultListener.onCancel(result);
                        }
                    }
                })
                .start();
    }

    /**
     * 录视频
     *
     * @param activity
     * @param onAlbumResultListener
     */
    public void recordVideo(Activity activity, final OnAlbumTakeResultListener onAlbumResultListener) {
        String id = ChatApp.getInstance().getUserId();
        String filePath = AlbumUtils.randomMP4Path(AlbumUtils.getAlbumVideoFile(activity, activity.getPackageName(), id));
        Album.camera(activity)
                .video()
                .setOutPutDir(activity.getPackageName(), id)
                .filePath(filePath)
                .quality(1)
                .limitDuration(Integer.MAX_VALUE)//15 * 1000
                .limitBytes(Integer.MAX_VALUE)//2560 * 1024L 2.5M


                .onResult(new Action<String>() {
                    @Override
                    public void onAction(@NonNull final String filePath) {
                        createSmallVideo(activity, filePath, onAlbumResultListener);
                    }


                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        if (onAlbumResultListener != null) {
                            onAlbumResultListener.onCancel(result);
                        }
                    }
                })
                .start();
    }

    public void createSmallVideo(Activity activity, @NonNull String filePath, OnAlbumTakeResultListener onAlbumResultListener) {
        createSmallVideo(activity, getAlbumFile(activity, filePath), onAlbumResultListener);
    }

    public void destroySmallVideo() {
        if (bar != null) {
            bar.dismiss();
            bar = null;
        }
    }

    public void createSmallVideo(Activity activity, @NonNull AlbumFile videoFile, OnAlbumTakeResultListener onAlbumResultListener) {
        if (activity == null || activity.isFinishing()) {
            return;
        }
        activity.runOnUiThread(() -> {
            if (onAlbumResultListener != null) {
                if (bar == null) {
                    bar = new NetProgressBarDialog(activity).setDes("加载中...");
                }
                if (!bar.isShowing()) {
                    bar.show();
                }
                ObserverThread.create().onBackGroudThread(new Runnable() {
                    @Override
                    public void run() {
                        sendThumbVideo(activity, videoFile, new OnAlbumTakeResultListener() {
                            @Override
                            public void onResult(AlbumFile albumFile) {
                                onAlbumResultListener.onResult(albumFile);
                                bar.dismiss();
                            }

                            @Override
                            public void onCancel(String result) {
                                onAlbumResultListener.onCancel(result);
                                bar.dismiss();
                            }
                        });
                    }
                });
            }
        });

    }

    /**
     * 发送压缩视频
     *
     * @param albumFile
     */
    public void sendThumbVideo(Activity activity, AlbumFile albumFile, OnAlbumTakeResultListener onAlbumResultListener) {
        String path = albumFile.getPath();
        String extension = path.substring(path.lastIndexOf(".") + 1, path.length());
        final String outputPath = path.substring(0, path.lastIndexOf(".")) + AlbumUtils.getMD5ForString(UUID.randomUUID().toString()) + "thumb." + extension;// + extension
        setVideoProcessor(activity, path, outputPath, new VideoProgressListener() {
            @Override
            public void onProgress(float progress) {
                if (progress == 1.0f) {
//                    double s = FileSizeUtil.getFileOrFilesSize(outputPath, FileSizeUtil.SIZETYPE_MB);
//                    JLog.d("压缩 size->" + outputPath + "," + s);
                    deleteFile(path);
                    //压缩结束
                    albumFile.setPath(outputPath);
                    if (!activity.isFinishing()) {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (onAlbumResultListener != null) {
                                    onAlbumResultListener.onResult(albumFile);
                                }
                            }
                        });
                    }

                } else if (progress == -1) {
                    albumFile.setPath(outputPath);
                    if (!activity.isFinishing()) {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (onAlbumResultListener != null) {
                                    onAlbumResultListener.onCancel("VideoProcessor err");
                                }
                            }
                        });
                    }
                }
            }
        });
    }

    /**
     * 文件地址转bean
     *
     * @param filePath
     * @param activity
     * @return
     */
    public AlbumFile getAlbumFile(Context activity, @NonNull String filePath) {
        return getAlbumFile(activity, filePath, null);
    }

    /**
     * 文件地址转bean
     *
     * @param filePath
     * @param activity
     * @return
     */
    public AlbumFile getAlbumFile(Context activity, @NonNull String filePath, String thumbPath) {
        ThumbnailBuilder tub = new ThumbnailBuilder(activity, activity.getPackageName(), ChatApp.getInstance().getUserId());
        File file = new File(filePath);
        AlbumFile albumFile = new AlbumFile();
        File parentFile = file.getParentFile();
        albumFile.setBucketName(parentFile.getName());

        String mimeType = AndroidFileUtil.getMimeType(file);// AlbumUtils.getMimeType(filePath);
        albumFile.setMimeType(mimeType);
        long nowTime = System.currentTimeMillis();
        albumFile.setAddDate(nowTime);
        albumFile.setSize(file.length());
        int type = AlbumTableBean.getFileType(filePath);
        if (AlbumTableBean.TYPE_VIDEO == type) {
            if (TextUtils.isEmpty(albumFile.getThumbPath())) {
                albumFile.setThumbPath(tub.createThumbnailForVideo(filePath));
            }
            albumFile.setPath(filePath);
            MediaPlayer player = new MediaPlayer();
            try {
                player.setDataSource(filePath);
                player.prepare();
                albumFile.setDuration(player.getDuration());
            } catch (Exception ignored) {
            } finally {
                player.release();
            }
        } else if (AlbumTableBean.TYPE_IMAGE == type) {
            if (FileSizeUtil.getFileOrFilesSize(filePath, FileSizeUtil.SIZETYPE_MB) >= 2.0d) {
                String newPath = albumFile.isOriginal() ? tub.createThumbnailForLimitImageLarge(filePath) : tub.createThumbnailForLimitImageMid(filePath);
                albumFile.setPath(newPath);
                if (TextUtils.isEmpty(albumFile.getThumbPath())) {
                    albumFile.setThumbPath(tub.createThumbnailForImage(newPath, thumbPath));
                }
                deleteFile(filePath);
            } else if (FileSizeUtil.getFileOrFilesSize(filePath, FileSizeUtil.SIZETYPE_KB) < 200.0d) {
                albumFile.setPath(filePath);
                albumFile.setThumbPath(filePath);
            } else {
                albumFile.setPath(filePath);
                if (TextUtils.isEmpty(albumFile.getThumbPath())) {
                    albumFile.setThumbPath(tub.createThumbnailForImage(filePath, thumbPath));
                }
            }
        } else {
            albumFile.setPath(filePath);
            albumFile.setThumbPath(filePath);
            if (!TextUtils.isEmpty(albumFile.getPath()) && AlbumTableBean.isRecordFile(albumFile.getPath())) {
                MediaPlayer player = new MediaPlayer();
                try {
                    player.setDataSource(albumFile.getPath());
                    player.prepare();
                    albumFile.setDuration(player.getDuration());
                } catch (Exception ignored) {
                } finally {
                    player.release();
                }
            }
        }
        albumFile.setMediaType(type);
        scanFile(null, albumFile.getPath(), albumFile.getThumbPath());
//        JLog.d(albumFile.getPath() + "," + FileSizeUtil.getFileOrFilesSize(filePath, FileSizeUtil.SIZETYPE_KB));
        return albumFile;
    }

    public AlbumFile getAlbumFileByTableRowId(Long fileId) {
        AlbumFile albumFile = new AlbumFile();
        AlbumTableBean a = AlbumTableBean.queryById(fileId);
        if (a != null) {
            albumFile.setBucketName(a.getMBucketName());
            albumFile.setMimeType(a.getMMimeType());
            albumFile.setAddDate(a.getMAddDate());
            albumFile.setSize(a.getMSize());
            albumFile.setMediaType(a.getMMediaType());
            albumFile.setThumbPath(a.getMThumbPath());
            albumFile.setPath(a.getMPath());
            albumFile.setDuration(a.getMDuration());
            return albumFile;
        }
        return null;
    }

    /**
     * 查看大头
     *
     * @param context
     * @param path
     */
    public void lookLargePhoto(Context context, String path) {
        try {
            LookLargePhotoDialog dialog = new LookLargePhotoDialog(context);
            dialog.getImageView().setImageBitmap(BitmapFactory.decodeFile(path));
//            GlideUtil.getInstance().load(path, dialog.getImageView());
            dialog.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public interface OnAlbumResultListener {
        void onResult(ArrayList<AlbumFile> albumFiles);

        void onCancel(String result);
    }

    public interface OnAlbumTakeResultListener {
        void onResult(AlbumFile albumFile);

        void onCancel(String result);
    }

    public interface OnAlbumBindResultListener {
        void onResult(boolean isOrigin, ArrayList<AlbumFile> albumFiles);

        void onCancel(String result);
    }

    /**
     * 开始voice动画
     *
     * @param imageView
     * @param isLeft
     */
    public void animStartVoice(ImageView imageView, boolean isLeft) {
        if (this.imageView != null) {
            animStopVoice(this.imageView, this.isLeft);
        }
        this.imageView = imageView;
        this.isLeft = isLeft;
        if (isLeft) {
            imageView.setImageResource(R.drawable.voice_play_anim_left);
        } else {
            imageView.setImageResource(R.drawable.voice_play_anim_right);
        }
        imageView.setTag(true);
        AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable();
        //开始动画
        animationDrawable.start();
    }

    private ImageView imageView;
    private boolean isLeft;

    public boolean isLeft() {
        return isLeft;
    }

    public void setLeft(boolean left) {
        isLeft = left;
    }

    public ImageView getImageView() {
        return imageView;
    }

    public void setImageView(ImageView imageView) {
        this.imageView = imageView;
    }

    /**
     * 结束voice动画
     *
     * @param imageView
     * @param isLeft
     */
    public void animStopVoice(ImageView imageView, boolean isLeft) {
        if (isLeft) {
            imageView.setImageResource(R.mipmap.icon_voice);
        } else {
            imageView.setImageResource(R.mipmap.dialog_icon_mic3_white);
        }
        imageView.setTag(false);
        this.imageView = null;
    }

    private MediaPlayer myPlayer = null;
    private String mVoicePath = null;
    private OnPlayAnimListener mOnPlayAnimListener;

    /**
     * 播放录音
     *
     * @param path
     * @param onPlayAnimListener
     */
    public void playVoice(String path, boolean isMac, OnPlayAnimListener onPlayAnimListener) {
        mOnPlayAnimListener = onPlayAnimListener;
        if (TextUtils.isEmpty(path) || path.equals(mVoicePath)) {
            stopVoice();
        } else {
            if (myPlayer != null) {
                myPlayer.release();
                myPlayer = null;
            }
            try {
                if (Utility.isFolderExist(path)) {
                    myPlayer = new MediaPlayer();
                    myPlayer.setAudioStreamType(isMac ? AudioManager.STREAM_VOICE_CALL : AudioManager.STREAM_MUSIC);
                    mVoicePath = path;
                    myPlayer.setDataSource(mVoicePath);// 设置数据源
                    myPlayer.prepare();// 准备
                    myPlayer.start(); // 开始播放

                    if (mOnPlayAnimListener != null) {
                        mOnPlayAnimListener.onStartAnim();
                    }
                    // 播放完毕回调方法
                    myPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            if (mOnPlayAnimListener != null) {
                                mOnPlayAnimListener.onStopAnim();
                            }
                        }
                    });
                } else {
                    myPlayer = null;
                    if (mOnPlayAnimListener != null) {
                        mOnPlayAnimListener.onStopAnim();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                if (myPlayer != null) {
                    myPlayer.release();
                    myPlayer = null;
                }
                if (mOnPlayAnimListener != null) {
                    mOnPlayAnimListener.onStopAnim();
                }
            }
        }
    }

    public void stopVoice() {
        mVoicePath = null;
        if (myPlayer != null) {
            if (myPlayer.isPlaying()) {
                myPlayer.stop();
            }
            myPlayer.release();
            myPlayer = null;
        }
        if (mOnPlayAnimListener != null) {
            mOnPlayAnimListener.onStopAnim();
        }
    }

    public interface OnPlayAnimListener {
        void onStartAnim();

        void onStopAnim();
    }

    /**
     * 将毫秒转时分秒
     *
     * @param time
     * @return
     */
    public static String generateTime(long time) {
        int totalSeconds = (int) (time / 1000);
        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;
        if (minutes == 0) {
            return String.format("%2d\"", seconds);
        } else if (hours == 0) {
            return String.format("%2d'%2d\"", minutes, seconds);
        }
        return hours > 0 ? String.format("%02dh%02d'%02d\"", hours, minutes, seconds) : String.format("%02d'%02d\"", minutes, seconds);
    }

    public static int getSeconds(long time) {
        int totalSeconds = (int) (time / 1000);
        return totalSeconds % 60;
    }

    /**
     * 设置饱和度
     *
     * @param imageView
     * @param saturation
     */
    public static void setImageColorMatrix(ImageView imageView, float saturation) {
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(saturation); // 设置饱和度:0为纯黑白，饱和度为0；1为饱和度为100，即原图；
        ColorMatrixColorFilter grayColorFilter = new ColorMatrixColorFilter(cm);
        imageView.setColorFilter(grayColorFilter);
    }

    /**
     * @param albumFile 文件插入文件表 转出主键
     * @return
     */
    public static Long insertAlbumFileToTable(AlbumFile albumFile, int mediaType) {
        return insertAlbumFileToTable(albumFile, mediaType, null);
    }

    public static Long insertAlbumFileToTable(AlbumFile albumFile, int mediaType, String url) {
        if (albumFile == null || TextUtils.isEmpty(albumFile.getPath())) {
            return -1L;
        }
        File file = new File(albumFile.getPath());
        if (!file.exists()) {
            return -1L;
        }
//        if (!TextUtils.isEmpty(url)) {
//            AlbumTableBean uOld = AlbumTableBean.queryByUrl(url);
//            if (uOld != null) {
//                deleteFile(uOld.getMPath(), uOld.getMThumbPath());
//            }
//        } else {
//            if (!TextUtils.isEmpty(albumFile.getPath())) {
//                AlbumTableBean uOld = AlbumTableBean.queryByPath(albumFile.getPath());
//                if (uOld != null) {
//                    deleteFile(uOld.getMPath(), uOld.getMThumbPath());
//                }
//            }
//        }
        AlbumTableBean tableBean = new AlbumTableBean();
        tableBean.setMMediaType(mediaType);
        tableBean.setMAddDate(albumFile.getAddDate());
        tableBean.setMBucketName(albumFile.getBucketName());
        tableBean.setMDuration(albumFile.getDuration());
        tableBean.setMMimeType(albumFile.getMimeType());
        tableBean.setMSize(albumFile.getSize());
        tableBean.setMPath(albumFile.getPath());
        if (TextUtils.isEmpty(url)) {
            tableBean.setMUrl(albumFile.getPath());
        } else {
            tableBean.setMUrl(url);
        }
        if (!TextUtils.isEmpty(albumFile.getThumbPath())) {
            tableBean.setMThumbPath(albumFile.getThumbPath());
        }
        return AlbumTableBean.insert(tableBean);
    }

    /**
     * 通过网络地址查询本地是否缓存过
     *
     * @param url
     * @return
     */
    public synchronized static AlbumTableBean getFileTableByPath(String url) {
        if (TextUtils.isEmpty(url)) {
            return null;
        }
        try {
            java.util.List<AlbumTableBean> list = DbController.getInstance().getRead().getAlbumTableBeanDao()
                    .queryBuilder().where(AlbumTableBeanDao.Properties.MUrl.eq(url)).list();
            if (list != null && !list.isEmpty()) {
                for (int i = 1; i < list.size() - 1; i++) {
                    AlbumTableBean b = list.get(i);
                    DbController.getInstance().getWrite().getAlbumTableBeanDao().delete(b);
                    deleteFile(b.getMPath(), b.getMThumbPath());
                }
                return list.get(list.size() - 1);
            }
            // url还是有不唯一的情况
//            return DbController.getInstance().getRead().getAlbumTableBeanDao()
//                    .queryBuilder().where(AlbumTableBeanDao.Properties.MUrl.eq(url)).unique();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }

    public static void deleteFile(String... paths) {
        if (paths != null && paths.length > 0) {
            for (String path : paths) {
                if (!TextUtils.isEmpty(path)) {
                    File file = new File(path);
                    if (file.exists()) {
                        file.delete();
                    }
                }
            }
            scanFile(null, paths);
        }
    }

    /**
     * @param albumFile 获取
     * @return
     */
    public static AlbumFile getAlbumFileByTable(AlbumTableBean albumFile) {
        if (albumFile == null) {
            return null;
        }
        AlbumFile tableBean = new AlbumFile();
        tableBean.setMediaType(albumFile.getMMediaType());
        tableBean.setAddDate(albumFile.getMAddDate());
        tableBean.setBucketName(albumFile.getMBucketName());
        tableBean.setDuration(albumFile.getMDuration());
        tableBean.setMimeType(albumFile.getMMimeType());
        tableBean.setSize(albumFile.getMSize());
        tableBean.setPath(albumFile.getMPath());
        tableBean.setThumbPath(albumFile.getMThumbPath());
        return tableBean;
    }


    public static String getImagePathByByteString(ByteString bytes) {
        String outPath = AlbumUtils.randomFilePath(ChatApp.getInstance(), ChatApp.getInstance().getPackageName(), ChatApp.getInstance().getUserId(), AlbumUtils.AlbumType.THUMB, ".album");
        return ByteStringUtil.getNewFilePath(outPath, bytes.asReadOnlyByteBuffer());
    }

    public void downLoadFileFriend(String url, int mediaType, String friendUserId, OnFileResponse onFileResponse) {
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(friendUserId)) {
            if (onFileResponse != null) {
                onFileResponse.onResult(null, "-1");
            }
            return;
        }
        DbController.getInstance().query(AlbumTableBean.class, AlbumTableBeanDao.Properties.MUrl.eq(url), new AsyncOperationListener() {
            @Override
            public void onAsyncOperationCompleted(AsyncOperation operation) {
                if (operation.isCompletedSucessfully()) {
                    AlbumTableBean atb = (AlbumTableBean) operation.getResult();
                    if (atb != null) {
                        String path = TextUtils.isEmpty(atb.getMThumbPath()) ? atb.getMPath() : atb.getMThumbPath();
                        if (!TextUtils.isEmpty(path)) {
                            File file = new File(path);
                            if (file.exists()) {
                                onFileResponse.onResult(atb.getMUrl(), "" + atb.getId());
                                return;
                            }
                        }
                    }
                    JLog.d(friendUserId + "--->" + url);
                    loadFriendFromNet(url, mediaType, friendUserId, onFileResponse);
                } else {
                    if (onFileResponse != null) {
                        onFileResponse.onResult(null, "-1");
                    }
                }
            }
        });
    }

    public void downLoadFileGroupMember(String url, int mediaType, String groupType, String groupId, String memberUserType, String groupMemberUserId, OnFileResponse onFileResponse) {
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(groupId) || TextUtils.isEmpty(groupMemberUserId)) {
            if (onFileResponse != null) {
                onFileResponse.onResult(null, "-1");
            }
            return;
        }
        DbController.getInstance().query(AlbumTableBean.class, AlbumTableBeanDao.Properties.MUrl.eq(url), new AsyncOperationListener() {
            @Override
            public void onAsyncOperationCompleted(AsyncOperation operation) {
                if (operation.isCompletedSucessfully()) {
                    AlbumTableBean atb = (AlbumTableBean) operation.getResult();
                    if (atb != null) {
                        String path = TextUtils.isEmpty(atb.getMThumbPath()) ? atb.getMPath() : atb.getMThumbPath();
                        if (!TextUtils.isEmpty(path)) {
                            File file = new File(path);
                            if (file.exists()) {
                                onFileResponse.onResult(atb.getMUrl(), "" + atb.getId());
                                return;
                            }
                        }
                    }
                    JLog.d(groupMemberUserId + "--->" + url);
                    downLoadFileGroupMemberNet(url, mediaType, groupType, groupId, memberUserType, groupMemberUserId, onFileResponse);
                } else {
                    if (onFileResponse != null) {
                        onFileResponse.onResult(null, "-1");
                    }
                }
            }
        });
    }

    public void downLoadFileFriendAvatar(String url, String friendUserId, OnFileResponse onFileResponse) {
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(friendUserId)) {
            if (onFileResponse != null) {//fileId为本地路径
                onFileResponse.onResult(null, null);
            }
            return;
        }
        String locPath = AlbumUtils.randomAvatarPath(ChatApp.getContext(), ChatApp.getContext().getPackageName(), TextUtils.isEmpty(ChatApp.getInstance().getUserId()) ? friendUserId : ChatApp.getInstance().getUserId(), url);
//        JLog.d(friendUserId+","+locPath);
        File file = new File(locPath);
        if (file.canRead()) {
            if (onFileResponse != null) {//fileId为本地路径
                onFileResponse.onResult(url, locPath);
            }
        } else {
            loadFriendFromNetAvatar(url, locPath, friendUserId, onFileResponse);
        }
    }

    private void loadFriendFromNet(String url, int mediaType, String friendUserId, OnFileResponse onFileResponse) {
        Context context = ChatApp.getInstance().getApplicationContext();
        AlbumUtils.AlbumType type = AlbumUtils.AlbumType.FILE;
        if (mediaType == AlbumTableBean.TYPE_IMAGE) {
            type = AlbumUtils.AlbumType.IMAGE;
        } else if (mediaType == AlbumTableBean.TYPE_RECORD_FILE) {
            type = AlbumUtils.AlbumType.RECORD;
        } else if (mediaType == AlbumTableBean.TYPE_VIDEO) {
            type = AlbumUtils.AlbumType.VIDEO;
        }
        String endxx = url.lastIndexOf(".") != -1 ? url.substring(url.lastIndexOf("."), url.length()) : "";
        String outPath = AlbumUtils.randomFilePath(context, context.getPackageName(), ChatApp.getInstance().getUserId(), type, endxx);
        OriginalPictureVideoFriendsTransmission down = OriginalPictureVideoTransmissionCreator.friend(ChatApp.getInstance().isRegister(), friendUserId, ChatApp.getInstance().getUserId(), mediaType == AlbumTableBean.TYPE_IMAGE);
        FileTransmissionManager.getInstance().buildDownloader()
                .friend(down)
                .serverPath(url)
                .targetPath(outPath)
                .onFileReceiver(new FileTransmissionListener.OnFileReceiverListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onProgress(int progress) {
                        if (onFileResponse != null) {
                            onFileResponse.onProgress(progress);
                        }
                    }

                    @Override
                    public void onComplete(String path) {
                        try {
                            JLog.d("insert path->" + url + "," + path);
                            ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Long>() {
                                @Override
                                public void onAction(Long obj) {
                                    if (onFileResponse != null) {
                                        onFileResponse.onResult(url, "" + obj);
                                    }
                                }

                                @Override
                                public Long onThreadAction() {
                                    return insertAlbumFileToTable(getAlbumFile(context, path), mediaType, url);
                                }
                            });

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        JLog.d("friend load err->" + msg);
                        if (onFileResponse != null) {
                            onFileResponse.onResult(url, "-1");
                        }
                    }
                }).download();
    }

    private void loadFriendFromNetAvatar(String url, String outPutPath, String friendUserId, OnFileResponse onFileResponse) {
        OriginalPictureVideoFriendsTransmission down = OriginalPictureVideoTransmissionCreator.avatar(ChatApp.getInstance().isRegister(), friendUserId);
        FileTransmissionManager.getInstance().buildDownloader()
                .friend(down)
                .serverPath(url)
                .targetPath(outPutPath)
                .onFileReceiver(new FileTransmissionListener.OnFileReceiverListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onProgress(int progress) {
                        if (onFileResponse != null) {
                            onFileResponse.onProgress(progress);
                        }
                    }

                    @Override
                    public void onComplete(String path) {
                        try {
                            JLog.d("create path->" + url + "," + path);
                            if (onFileResponse != null) {
                                onFileResponse.onResult(url, path);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        JLog.d("friend load err->" + msg);
                        if (onFileResponse != null) {
                            onFileResponse.onResult(url, "-1");
                        }
                    }
                }).download();
    }

    public void downLoadFileFriend(String url, String friendId, ImageView imageView) {
//        GlideUtil.getInstance().load(R.mipmap.pic_user_avatar_default_36dp, imageView);
        downLoadFileFriend(url, friendId, imageView, ContextCompat.getDrawable(imageView.getContext(), R.mipmap.pic_user_avatar_default_36dp));
    }

    public void downLoadFileFriend(String url, String friendId, ImageView imageView, Drawable drawable) {
        downLoadFileFriendAvatar(url, friendId, new OnFileResponse() {
            @Override
            public void onResult(String url, String fileId) {
                if (TextUtils.isEmpty(fileId)) {
//                    GlideUtil.getInstance().clear(imageView);
                    imageView.setImageDrawable(drawable);
                    return;
                }
                File file = new File(fileId);
                if (!file.exists()) {
                    imageView.setImageDrawable(drawable);
                    return;
                }
                String tag = (String) imageView.getTag(com.nic.view.R.id.glide_image_id);
                if (TextUtils.isEmpty(tag) || tag.equals(url)) {
                    imageView.setTag(com.nic.view.R.id.glide_image_id, url);
                }
                GlideUtil.getInstance().load(fileId, imageView);
            }
        });
    }

    /**
     * 群成员文件下载
     *
     * @param url
     * @param mediaType
     * @param groupType
     * @param groupId
     * @param memberUserType
     * @param groupMemberUserId
     * @param onFileResponse
     */
    public void downLoadFileGroupMemberNet(String url, int mediaType, String groupType, String groupId, String memberUserType, String groupMemberUserId, OnFileResponse onFileResponse) {
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(groupId) || TextUtils.isEmpty(groupMemberUserId)) {
            return;
        }
        Context context = ChatApp.getInstance().getApplicationContext();
        AlbumUtils.AlbumType type = AlbumUtils.AlbumType.FILE;
        if (mediaType == AlbumTableBean.TYPE_IMAGE) {
            type = AlbumUtils.AlbumType.IMAGE;
        } else if (mediaType == AlbumTableBean.TYPE_RECORD_FILE) {
            type = AlbumUtils.AlbumType.RECORD;
        } else if (mediaType == AlbumTableBean.TYPE_VIDEO) {
            type = AlbumUtils.AlbumType.VIDEO;
        }
        String endxx = url.lastIndexOf(".") != -1 ? url.substring(url.lastIndexOf("."), url.length()) : "";
        String outPath = AlbumUtils.randomFilePath(context, context.getPackageName(), ChatApp.getInstance().getUserId(), type, endxx);
        OriginalPictureVideoGroupTransmission down = OriginalPictureVideoTransmissionCreator.group(IMSContacts.UserType.REGISTERED_USER.equals(groupType), IMSContacts.UserType.REGISTERED_USER.equals(memberUserType), ChatApp.getInstance().isRegister(), groupId, groupMemberUserId, ChatApp.getInstance().getUserId(), mediaType == AlbumTableBean.TYPE_IMAGE);
        FileTransmissionManager.getInstance().buildDownloader()
                .group(down)
                .serverPath(url)
                .targetPath(outPath)
                .onFileReceiver(new FileTransmissionListener.OnFileReceiverListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onProgress(int progress) {
                        if (onFileResponse != null) {
                            onFileResponse.onProgress(progress);
                        }
                    }

                    @Override
                    public void onComplete(String path) {
                        try {
                            ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Long>() {
                                @Override
                                public void onAction(Long obj) {
                                    if (obj != null) {
                                        if (onFileResponse != null) {
                                            onFileResponse.onResult(url, "" + obj);
                                        }
                                    }
                                }

                                @Override
                                public Long onThreadAction() {
                                    return insertAlbumFileToTable(getAlbumFile(context, path), mediaType, url);
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {

                    }
                }).download();
    }


    public abstract static class OnFileResponse implements IFileResponse {
        @Override
        public void onProgress(int progress) {
        }
    }

    public interface IFileResponse {
        void onProgress(int progress);

        void onResult(String url, String fileId);
    }
}
